<template>
  <div class="upload-container">
    <el-upload
      :data="dataObj"
      :headers="headers"
      :multiple="false"
      :show-file-list="false"
      :on-success="handleImageSuccess"
      class="image-uploader"
      :action="commonUploadAction"
    >
        <img v-if="imageUrl" style="width:40px;height:40px;" :src="imageUrl" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
  </div>
</template>

<script>
import { getToken } from '@/api/qiniu'
import 'video.js/dist/video-js.css'

import { videoPlayer } from 'vue-video-player'
import { number } from 'echarts/lib/export'

export default {
  name: 'SingleImageUpload',
  props: {
    value: {
      type: String,
      default: ''
    },
    imgHeight: {
        type: Number,
        default: 100
    },
    imgMarginTop: {
        type: Number,
        default: 0
    },
  },
  data() {
    return {
      tempUrl: '',
      commonUploadAction: process.env.VUE_APP_UPLOAD_BASE_URL + 'api/v1/file/upload',
      dataObj: { token: this.$store.getters['user/token'], key: '' },
      headers: { Authorization: this.$store.getters['user/token']},
    }
  },
  components: {
    videoPlayer
  },
  computed: {
    imageUrl() {
      return this.value
    },
    imgStyle() {
        console.log('height: ' + this.imgHeight + '% !important;margin-top: ' + this.imgMarginTop + '% !important;');
        return 'height: ' + this.imgHeight + '% !important;margin-top: ' + this.imgMarginTop + '% !important;'
    },
  },
  created() {

  },
  methods: {
    rmImage() {
      this.emitInput('')
    },
    emitInput(val) {
      this.$emit('input', val)
    },
    handleImageSuccess(res, file) {
      if (res.success === true)
      {
        this.tempUrl = res.data.path;
      }

      this.emitInput(this.tempUrl)
    },
    beforeUpload() {
      const _self = this
      return new Promise((resolve, reject) => {
        getToken().then(response => {
          const key = response.data.qiniu_key
          const token = response.data.qiniu_token
          _self._data.dataObj.token = token
          _self._data.dataObj.key = key
          this.tempUrl = response.data.qiniu_url
          resolve(true)
        }).catch(err => {
          console.log(err)
          reject(false)
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
    .image-uploader {width: 100%;height: 36px;padding: 0px;margin:0px;}
</style>
